package com.mm.base.config.web;

import cn.hutool.json.JSONUtil;
import com.mm.util.result.DResult;
import com.mm.util.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 自定义MVC异常处理器
 * @Date 2023/9/27 下午2:31
 * @Author yanglin
 **/
@Slf4j
public class WebMvcExceptionResolver extends AbstractHandlerExceptionResolver {

    /**
     * 异常解析器的顺序， 数值越小，表示优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return -99;
    }

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.error("WebMvcExceptionResolver doResolveException == {}, {}", request.getRequestURL(), ex.getMessage());
        try {
            DResult result = DResult.failed(ResultCode.SYSTEM_EXECUTION_ERROR.getCode(), ex.getMessage());
            response.getWriter().write(JSONUtil.toJsonStr(result));
        } catch (IOException e) {
        }
        return new ModelAndView();
    }
}
